<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal='false' fullscreen center append-to-body>
    <el-button class="miui-dialog-close-btn" @click="dialogFormVisible = false">关闭页面</el-button>

    <el-form ref="dataForm" :model="dataForm" inline :rules="rules" :disabled="display">
      <el-row>
        <el-col :span="8">
            <el-form-item label="就读学校" prop="schoolId">
              <el-select v-model="dataForm.schoolId" clearable filterable default-first-option placeholder="输入学校名字查找" @change="getGradeList(dataForm.schoolId)">
                <el-option v-for="item in schoolOptions" :value="item.id" :label="item.schoolName" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="就读年级" prop="gradeId">
            <el-select v-model="dataForm.gradeId" @change="getClassList">
              <el-option v-for="item in gradeOptions" :value="item.id" :label="item.gradeName" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="就读班级" prop="classId">
            <el-select v-model="dataForm.classId">
              <el-option v-for="item in classOptions" :value="item.id" :label="item.className" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="dataForm.studentName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出生日期" prop="birthDay">
            <el-input v-model="dataForm.birthDay"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学生性别" prop="gender">
            <el-radio-group v-model="dataForm.gender">
              <el-radio-button :label="0">男</el-radio-button>
              <el-radio-button :label="1">女</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="身份证号" prop="certificateNum">
            <el-input v-model="dataForm.certificateNum"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学年开始" prop="fromYear">
            <el-input v-model="dataForm.fromYear"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学年结束" prop="toYear">
            <el-input v-model="dataForm.toYear"></el-input>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="学生学号" prop="sno">
            <el-input v-model="dataForm.sno"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话" prop="telPhone">
            <el-input v-model="dataForm.telPhone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学生状态" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio v-for="(item,index) in statusOption" :label="item.value" :key="index">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" v-if="!display">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit()">提 交</el-button>
    </div>

    <!-- 弹窗，选择学校 -->
    <search-school v-if="schoolVisible" ref="schoolDialog" @refreshForm="getSchoolData"></search-school>
  </el-dialog>
</template>

<script>
  import { remote } from '@/api/admin/dict'

  // import { getTeacherObj, addObj, putObj, checkTeacherCode } from '@/api/pvm/teacher'

  // import { getSchoolObj, getSchoolDeptList } from '@/api/pvm/school'
  import { getSchoolList, getClassOptions,getSchoolObj } from '@/api/pvm/school'
  import {getGradeBySchoolId} from '@/api/pvm/grade'
  import { getObj, addObj, putObj } from '@/api/pvm/student'

  import SearchSchool from '../teacher/components/SearchSchool'

  export default {
    name: 'add',
    data() {
      return {
        title: '',
        type: '',
        display: false,
        dialogFormVisible: false,
        dataForm: {
          schoolId: '',
          gradeId: '',
          classId: '',
          sno: '',
          studentName: '',
          gender: '0',
          telPhone: '',
          birthDay: '',
          status: '',
          certificateNum: '',
          fromYear: '',
          toYear: '',
          status: ''
        },
        deptOptions: [],
        schoolOptions: [],
        gradeOptions: [],
        classOptions: [],
        statusOption: [],
        rules: {
          schoolId: [{required: true,message: '请选择就读学校',trigger: 'blur'}],
          gradeId: [{required: true,message: '请选择就读年级',trigger: 'blur'}],
          classId: [{required: true,message: '请选择就读班级',trigger: 'blur'}],
          // sno: [{required: true,message: '请输入学生学号',trigger: 'blur'}],
          studentName: [{required: true,message: '请输入学生姓名',trigger: 'blur'}],
          birthDay: [{required: true,message: '请输入学生出生日期',trigger: 'blur'}],
          gender: [{required: true,message: '请选择学生性别',trigger: 'blur'}],
          // telPhone: [{required: true,message: '请输入联系电话',trigger: 'blur'}],
          certificateNum: [{required: true,message: '请输入学生身份证号',trigger: 'blur'}],
          fromYear: [{required: true,message: '请输入学年开始',trigger: 'blur'}],
          toYear: [{required: true,message: '请输入学年结束',trigger: 'blur'}],
          status: [{required: true,message: '请选择学生状态',trigger: 'blur'}]
        },
        schoolVisible: false
      }
    },
    components: {
      SearchSchool
    },
    methods: {
      /*
       * params {id} ID，不存在时为新增
       * params {type} 表单类型 "add":新增 "edit":编辑 "check":查看
       */
      init(id, type) {
        this.type = type
        this.dialogFormVisible = true;
        if(type == 'check'){
          this.display = true
        }else{
          this.display = false
        }
        //  根据type确定弹窗标题
        switch(type){
          case 'add': {
            this.title = '学生新增'
            break;
          };
          case 'edit': {
            this.title = '学生编辑'
            break;
          };
          case 'check': {
            this.title = '学生详情'
            break;
          };
        }
        this.getSchoolOptions()
        this.getStatusList()
        //  初始化表单信息
        for(let key in this.dataForm){
          this.dataForm[key] = ''
        }
        // 设置初始值
        this.$set(this.dataForm,'id',id)
        this.$set(this.dataForm,'gender',0)
        this.$set(this.dataForm,'status',0)
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if(this.dataForm.id){
            getObj(this.dataForm.id).then(res => {
              if(res.data.code == '0'){
                this.dataForm = res.data.data
                getSchoolObj(this.dataForm.schoolId).then(response => {
                  if(response.data.code == '0'){
                    this.$set(this.dataForm,'schoolName',response.data.data.schoolName)
                    this.$set(this.dataForm,'schoolCode',response.data.data.schoolCode)
                  }else{
                    this.$message.error(response.data.msg)
                  }
                })
                getGradeBySchoolId(this.dataForm.schoolId).then(response => {
                  if(response.data.code == '0'){
                    this.gradeOptions = response.data.data
                  }else{
                    this.$message.error(response.data.msg)
                  }
                })
                getClassOptions(this.dataForm.schoolId,this.dataForm.gradeId).then(response => {
                  if(response.data.code == '0'){
                    this.classOptions = response.data.data
                  }else{
                    this.$message.error(response.data.msg)
                  }
                })
              }else{
                this.$message.error(res.data.msg)
              }
            })
          }
        })
      },
      //提交按钮
      onSubmit: function() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if(this.dataForm.id){
              putObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.dialogFormVisible = false
                  this.$message.success('编辑成功')
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
              }).catch(() => {
                alert('编辑失败，请联系管理员')
              })
            }else{
              addObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.dialogFormVisible = false
                  this.$message.success('添加成功')
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
              }).catch(() => {
                alert("添加失败，请联系管理员")
              });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      // 查询学校列表
      getSchoolOptions(){
        getSchoolList().then(response => {
          if(response.data.code == '0'){
            this.schoolOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 查询年级列表
      getGradeList(schoolId){
        this.gradeOptions = []
        this.classOptions = []
        this.$set(this.dataForm,'gradeId','')
        this.$set(this.dataForm,'classId','')
        getGradeBySchoolId(schoolId).then(response => {
          if(response.data.code == '0'){
            this.gradeOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 查询班级列表
      getClassList(val){
        this.classOptions = []
        this.$set(this.dataForm,'classId','')
        getClassOptions(this.dataForm.schoolId,val).then(response => {
          if(response.data.code == '0'){
            this.classOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取学生状态列表
      getStatusList(){
        remote('student_status').then(response => {
          let responseData = response.data.data
          let list = []
          responseData.forEach(item => {
            list.push({label: item.label, value: item.value*1})
          })
          this.statusOption = list
        })
      }
    }
  }
</script>
